<?php
/*
 * description：
 * author：wh
 * email：
 * createTime：{2020/11/11} {10:23} 
 */

namespace wanghua\general_utility_tools_php\log\driver;

/**
 * MySQL日志驱动
 *
 * 说明：日志记录在mysql数据库，把日志记录在数据库中；不建议记录大量日志。
 * 推荐记录诸如系统生命周期日志、临时调试日志等少量日志，因为日志将占用大量空间，存在数据库中可能降低MySQL效率
 *
 * 用法参考：general_utility_tools_php\src\log\Driver.php类
 *
 * 仅支持ThinkPHP框架
 *
 * DDL:
Create Table If Not Exists `t_sys_period_log` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
`url` varchar(150) COLLATE utf8mb4_general_ci DEFAULT '' COMMENT 'URL(不含查询参数)',
`time` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' COMMENT '当前时间(微秒)',
`use` int(10) unsigned DEFAULT '0' COMMENT '消耗(微秒)',
`all` int(10) unsigned DEFAULT '0' COMMENT '总消耗(微秒)',
`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '当前时间',
`ip` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' COMMENT 'IP',
`reqid` varchar(16) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '请求ID',
`user_agent` varchar(3000) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' COMMENT '代理',
`input` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci COMMENT '输入',
`log_info` text COLLATE utf8mb4_general_ci COMMENT '日志内容',
PRIMARY KEY (`id`),
KEY `index_create_time` (`create_time`) USING BTREE,
KEY `index_time` (`time`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='系统周期日志';
 *
 * Class Mysql
 * @package wanghua\general_utility_tools_php\log
 */
class Mysql extends Base
{
    //日志数据
    private $log_data = [];
    //日志数据表前缀:
    //如果没有前缀，可能和已有表名称冲突
    private $table = 't_sys_period_log';//默认表

    public function __construct()
    {
        parent::__construct();

            //初始化日志
            $this->initLogTable();
    }

    /**
     * desc：初始化日志表
     *
     * author：wh
     * @return mixed
     */
    private function initLogTable(){
        $ddl = "Create Table If Not Exists `t_sys_period_log` (
  `id` int unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `url` varchar(150) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' COMMENT 'URL(不含查询参数)',
  `time` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' COMMENT '当前时间(微秒)',
  `use` int unsigned DEFAULT '0' COMMENT '消耗(微秒)',
  `all` int unsigned DEFAULT '0' COMMENT '总消耗(微秒)',
  `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '当前时间',
  `ip` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' COMMENT 'IP',
  `reqid` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '请求ID',
  `user_agent` varchar(3000) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' COMMENT '代理',
  `input` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci COMMENT '输入',
  `log_info` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci COMMENT '日志内容',
  PRIMARY KEY (`id`),
  KEY `index_create_time` (`create_time`) USING BTREE,
  KEY `index_time` (`time`) USING BTREE,
  KEY `index_all` (`all`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='系统周期日志';";

        if(!\think\Cache::get('mysql_init_log_table_cache')){
            \think\Db::execute($ddl);
            \think\Cache::set('mysql_init_log_table_cache',1);//1存在
        }
    }

    /**
     * desc：设置日志表名
     *
     * author：wh
     * @param $tab
     */
    function setTable($tab){
        $this->table = $tab;
    }

    /**
     *
     * desc：获取日志表名
     *
     * author：wh
     * @return string
     */
    function getTable(){
        return $this->table;
    }

    /**
     * desc：写日志
     *
     * 写进内存
     *
     * author：wh
     * @param $content
     */
    function write($content){
        parent::write($content);
        $log_len = count($this->log_data);
        $time = $this->getMicrosecond();
        $use = $log_len>0?$time-$this->log_data[$log_len-1]['time']:0;
        //data
        $this->log_data[] = [
            'url'=>request()->domain().request()->baseUrl(),
            'time'=>$this->getMicrosecond(),
            'ip'=>request()->ip(),
            'reqid'=>$this->getReqID(),
            'use'=>$use,//单次消耗
            'all'=>array_sum(array_column($this->log_data, 'use'))+$use,
            'user_agent'=>json_encode(request()->header(),JSON_UNESCAPED_UNICODE),
            'input'=>json_encode(input(), JSON_UNESCAPED_UNICODE),
            'log_info'=>json_encode($content, JSON_UNESCAPED_UNICODE),
        ];
    }

    /**
     * desc：持久化
     *
     * author：wh
     */
    function flush()
    {
        parent::flush();
        return \think\Db::table($this->getTable())->insertAll($this->log_data);
    }

    /**
     * desc：获取日志数据
     * author：wh
     * @return array|void
     */
    function getLogData()
    {
        parent::getLogData();
        return $this->log_data;
    }
}